
var defaultParameter = {
  pageNumber: 1,
  pageSize: 20
};

var statusData=new Array();
var purchWayData=new Array();
var purchTypeData = new Array();

function initPlan(){
 var param={hhh:123};
  var client = new com.im.common.ajax();
  var result = client.callAsJson("projectInfoService/queryPlanProjList",param );

  console.log(result);
  if(!result.success){
    toastr.error(result.resultMsg);
  }else{
     result.result.rows.unshift({'planProjId':'','planProjName':'全部'});
    $.each( result.result.rows, function (i) {
      $('#belongPlan').append("<option value=" + result.result.rows[i].planProjId + ">" +result.result.rows[i].planProjName + "</option>");

    });
    $("#belongPlan").select2({});
  }



}

function initPurchWay(){
  var client = new com.im.common.ajax();
  var param={};
  param.constParamCode="PURCH_WAY";
  var result = client.callAsJson("busiConstService/queryBusiConstList",param );
  console.log(result);
   if(!result.success){
      toastr.error(result.resultMsg);
    }else{
       purchWayData=result.result;
       result.result.unshift({'paramValValue':'','paramValName':'请选择'});
      $.each( result.result, function (i) {
        $('#purchWay').append("<option value=" + result.result[i].paramValValue + ">" +result.result[i].paramValName + "</option>");

      });
      $("#purchWay").select2({});
    }
}

function initPurchType(){
  var client = new com.im.common.ajax();
  var param={};
  param.constParamCode="PURCH_TYPE";
  var result = client.callAsJson("busiConstService/queryBusiConstList",param );
  if(!result.success){
    toastr.error(result.resultMsg);
  }else{
    purchTypeData=result.result;
    result.result.unshift({'paramValValue':'','paramValName':'请选择'});
    $.each( result.result, function (i) {
      $('#purchPlanType').append("<option value=" + result.result[i].paramValValue + ">" +result.result[i].paramValName + "</option>");

    });
    $("#purchPlanType").select2({});
  }
}


function initStatus(){
  var client = new com.im.common.ajax();
  var param={};
  param.tabName="T_PURCHASE_PLAN";
  param.colName="STATUS_CD";
  var result = client.callAsJson("commonService/queryTabColParam",param);
   if(!result.success){
        toastr.error(result.resultMsg);
      }else{
         result.result.unshift({'colVal':'','colValName':'全部'});
         statusData=result.result;
        $.each( result.result, function (i) {
          $('#statusCd').append("<option value=" + result.result[i].colVal + ">" +result.result[i].colValName + "</option>");
          if(result.result[i].colVal != 50){
        	  $('#purchaseStatusCd').append("<option value=" + result.result[i].colVal + ">" +result.result[i].colValName + "</option>");
          }
        });
        $("#statusCd").select2({});
        $("#purchaseStatusCd").select2({});
      }
}

function initTable(){

  var columns=[[
   {
                field : 'ck',
                checkbox : true
    },
   {field:'purchPlanId',title:'计划id',fitColumns:true,hidden:true,
   },
    {field:'impleProjId',title:'项目id',fitColumns:true,hidden:true,
    },
    {field:'impleProjName',title:'实施项目名称',width:150,fitColumns:true,align:'left'
    },
    // {field:'purchPlanName',title:'采购计划名称', width:150,fitColumns:true,align:'left'
    // },


  {field:'purchPlanName',title:"采购计划名称", width:150,fitColumns:true,align:'left',
      formatter: function(value,row,index){
          if(row.fileUploads!=null && row.fileUploads.length>0){
              var html="";
              for(var i=0;i<row.fileUploads.length;i++){
                  html+="<span style='cursor:pointer'><u><a onclick='downloadFile(\""+row.fileUploads[i].filePath+"\",\""+row.fileUploads[i].uploadName+"\")'>"+row.purchPlanName+"</a></u></span><br>";
              }
              return html;
          }else{
              return row.purchPlanName;
          }
      }
  },
//    {field:'purchPlanNum',title:"计划编号",width:$(this).width()*0.1,fitColumns:true,
//     },
    {field:'purchWay',title:"采购方式",width:60,fitColumns:true,
          formatter: function (value, row, index) {
             for(var i=0;i<purchWayData.length;i++){
               if(value!='' && value==purchWayData[i].paramValValue){
                 return purchWayData[i].paramValName;
               }
             }
             return "";
          },
     },
    {field:'prepayTotal',title:"预算金额（万元）",width:70,fitColumns:true,
     },
    {field:'planType',title:"计划类型",width:70,fitColumns:true,
      formatter: function (value, row, index) {
        for(var i=0;i<purchTypeData.length;i++){
          if(value!='' && value==purchTypeData[i].paramValValue){
            return purchTypeData[i].paramValName;
          }
        }
        return "";
      }
    },
    {field:'agentOrg',title:'代理机构',width:100,fitColumns:true,hidden:true,

    },
    {field:'orgName',title:'代理机构',width:100,fitColumns:true,align:'left'

    },

    {field:'giveDt',title:"下达时间",width:60,fitColumns:true,
      },
    {
      field: 'statusCd',
      title: "状态",
      width: 60,
      fitColumns: true,
      formatter: function (value, row, index) {
         for(var i=0;i<statusData.length;i++){
           if(value==statusData[i].colVal){
             return statusData[i].colValName;
           }
         }
         return "";
      },
    },
    {field:'operation',title:"操作",width:30,
      formatter: function(value,row,index){
        if(row.statusCd==10 || row.statusCd==30){
         return '<a class="edit" href="javascript:void(0)" title="编辑" onclick="updatePurchasePlan(' + index + ')"> <i class="fa fa-edit"></i></a>'
              + '<a class="remove" href="javascript:void(0)" title="上传" onclick="uploadFileModel(' + index +')"><i class="fa fa-upload"></i></a>';
//             +
//             '<a class="remove" href="javascript:void(0)" title="删除" onclick="delPurchasePlanConfirm('
//             + index
//             + ')"><i class="fa fa-trash"></i></a>';
        }else{
           return '<a class="edit disabled" href="javascript:void(0)" title="编辑"> <i class="fa fa-edit"></i></a>'
                + '<a class="remove" href="javascript:void(0)" title="上传" onclick="uploadFileModel(' + index +')"><i class="fa fa-upload"></i></a>';
//         return '<a class="edit" href="javascript:void(0)" title="编辑"> <i class="fa fa-edit"></i></a>';
//             +
//             '<a class="remove" href="javascript:void(0)" title="删除" ><i class="fa fa-trash"></i></a>';
        }

    }},
  ]];

  $('#planList').datagrid({
    url:'/InfoManageWeb/purchaseService/queryPurchasePlanListByCondition',
    method:'post',
    dataType : 'json',
    rownumbers:true,
    checkOnSelect:true,
    queryParams:defaultParameter,
    pagination:true,
    nowrap:false,
    fitColumns:true,
    columns:columns,
    loadMsg:'数据加载中，请耐心等待',
    onBeforeLoad : function(param){
    for (var key in param) {
    if(key=="rows"){
    delete param[key];
    }
    }
    },
    loadFilter:function(data){
      if(data.resultCode!=0){
        toastr.error(data.resultCode);
        return null;
      }else{
        return data.result;
      }
    },
//    onCheck:function(index,row){
//      if(row.statusCd!= 10 && row.statusCd!=30){
//      $("#planList").datagrid("uncheckRow",index);
//      toastr.info("只有待审核和初审不通过才能选中删除");
//      }
//    },
//    onCheckAll:function(rows){
//     for(var i=0;i<rows.length;i++){
//      var row=rows[i];
//      if(row.statusCd!= 10 && row.statusCd!=30){
//      var index=$("#planList").datagrid("getRowIndex",row);
//      $("#planList").datagrid("uncheckRow",index);
//      toastr.info("只有待审核和初审不通过才能选中删除");
//      }
//     }
//    },
//    onLoadSuccess: function (data) {
//      //模拟测试加载成功后数据Id大于20的都勾选中，并禁用checkbox
//      for (var i = 0; i < data.rows.length; i++) {
//        if (data.rows[i].statusCd!= 10 && data.rows[i].statusCd!=30) {
//          $(".datagrid-row[datagrid-row-index=" + i + "] input[type='checkbox']")[0].disabled = true;
//        }
//      }
//    }
  });
  var p = $('#planList').datagrid('getPager');
  $(p).pagination({
    pageSize: 20,//每页显示的记录条数，默认为10
    pageList: [10,20,30],//可以设置每页记录条数的列表
    beforePageText: '第',//页数文本框前显示的汉字
    afterPageText: '页    共 {pages}  页',
    displayMsg: '当前显示 {from} - {to} 条记录 共 {total}  条记录',
    onSelectPage:function(pageNumber, pageSize){
      defaultParameter.pageNumber=pageNumber;
      defaultParameter.pageSize=pageSize;
      var planProjClass=$("#planProjClass").val();
      var implProjectId=$("#implProjectId").val();
      var statusCd=$("#purchaseStatusCd").val();
      var orgId=$("#orgId").val();
        var startDt=$("#startDt").val();
        var endDt=$("#endDt").val();
     // defaultParameter.implProjectId=implProjectId;
        defaultParameter.implProjectId=implProjectId;
      defaultParameter.planProjClass=planProjClass;
      defaultParameter.orgId=orgId;
      defaultParameter.startDt=startDt;
      defaultParameter.endDt=endDt;
      defaultParameter.statusCd=statusCd;
      $('#planList').datagrid('reload',defaultParameter);
    }
  });
}

function downloadFile(path,realName){
    location.href="/FileManageWeb/fileController/downloadFile?fileName="+path+"&realName="+encodeURI(encodeURI(realName));
}

function updatePurchasePlan(index){
  var row = $('#planList').datagrid('getData').rows[index];
  $('#purchasePlanModal').modal("show");
  $("#purchPlanId").val(row.purchPlanId);
  $("#implProjectInfo").val(row.impleProjId);
  // $("#projectNameText").val(row.impleProjName);
  $("#purchPlanCode").val(row.purchPlanNum);
  $("#purchPlanName").val(row.purchPlanName.substring(row.purchPlanName.indexOf("】-") + 2));
  $("#purchWay").val(row.purchWay).trigger("change");
  $("#purchPlanType").val(row.planType).trigger("change");
  $("#prePayTotal").val(row.prepayTotal);
  $("#giveDt").val(row.giveDt);
  $("#statusCd").val(row.statusCd).trigger("change");
  $("#orgList").val(row.agentOrg).trigger("change");
  $("#description").val(row.description);
  disableModelField()
}

function disableModelField(){
//  $("#orgBtn1").attr("disabled", true);
//  $("#itemBtn").attr("disabled", true);
  $("#orgInfo").prop("disabled", true);
  $("#planProjClassInfo").prop("disabled", true);
  $("#purchPlanCode").attr("readonly", true);
//  $("#purchPlanName").prop("disabled", true);
//  $("#purchWay").prop("disabled", true);
//  $("#orgList").prop("disabled",true);
}

function availableModelField(){
//  $("#orgBtn1").attr("disabled", false);
//    $("#itemBtn").attr("disabled", false);
  $("#purchPlanCode").attr("readonly", false);
  $("#orgInfo").prop("disabled", false);
  $("#planProjClassInfo").prop("disabled", false);
//  $("#purchPlanName").prop("disabled", false);
//  $("#purchWay").prop("disabled", false);
//  $("#orgList").prop("disabled",false);
}

function savePurchasePlan(){
  var param = {};
  var purchPlanId=$("#purchPlanId").val();
  var url = "/purchaseService/addPurchasePlan";
  if (purchPlanId != null && purchPlanId != "") {
    url = "/purchaseService/updatePurchasePlan";
    param.purchPlanId=purchPlanId;
  }
  var formValidator = $('#purchasePlanForm').data('bootstrapValidator');
  formValidator.options.excluded = [':disabled'];
  formValidator.validate();

  if (formValidator.isValid()) {
     param.impleProjId=$("#implProjectInfo").val();
     param.purchPlanNum=$("#purchPlanCode").val();
     param.purchPlanName=$("#purchPlanName").val();
     param.planType=$("#purchPlanType").val();
     param.purchWay=$("#purchWay").val();
     param.prepayTotal=$("#prePayTotal").val();
     param.giveDt=$("#giveDt").val();
     param.statusCd=$("#statusCd").val();
     param.description=$("#description").val();
     param.agentOrg=$("#orgList").val();
     var client = new com.im.common.ajax();
     var result = client.callAsJson(url,param);
      if(result.resultCode!=0){
        toastr.error(result.resultCode);
       }else{
          $('#purchasePlanModal').modal('hide');
            queryPurchasePlan();
       }

  }
}

function delPurchasePlanConfirm(index){
	var purchPlanIds = new Array();
	var uncheckMsg = "";
	$.each($('#planList').datagrid('getChecked'), function(index, item){
		if(item.statusCd!= 10 && item.statusCd!=30){
			if(uncheckMsg == ''){
				uncheckMsg += (index+1);
			}else{
	    		uncheckMsg += ',' + (index+1);
			}
		}else{
			purchPlanIds.push(item.purchPlanId);
		}
	});
	if(uncheckMsg != '' && purchPlanIds.length == 0){
		toastr.info("第"+ uncheckMsg + '行数据不能删除，请重新选择');
		return;
	}else if(uncheckMsg == '' && purchPlanIds.length == 0){
		toastr.info('请选中至少一行记录再删除');
		return;
	}else if(uncheckMsg != '' && purchPlanIds.length != 0){
		toastr.info("提示：第"+ uncheckMsg + '行数据不能删除');
	}
    var param={};
    param.purchPlanIds=purchPlanIds;
    com.im.common.confirm('确认删除采购计划？',param,"delPurchasePlan");
}

function delPurchasePlan(param){
  url = "/purchaseService/deletePurchasePlanByIds";
  var client = new com.im.common.ajax();
  var result = client.callAsJson(url,param);
  if(!result.success) {
    toastr.error(result.resultMsg);
  }else{
    queryPurchasePlan();
  }

}

function reset(){
  $("#belongPlan").val("").trigger("change");
  $("#projuectOut").val("");
  $("#planName").val("");
  $("#unitOut").val("").trigger("change");
}

function queryPurchasePlan(){
  var planProjClass=$("#planProjClass").val();
  var implProjectId=$("#implProjectId").val();
  var statusCd=$("#purchaseStatusCd").val();
  var orgId=$("#orgId").val();
  var startDt=$("#startDt").val();
  var endDt=$("#endDt").val();
  defaultParameter.implProjectId=implProjectId;
  defaultParameter.planProjClass=planProjClass;
  defaultParameter.orgId=orgId;
  defaultParameter.startDt=startDt;
  defaultParameter.endDt=endDt;
  defaultParameter.statusCd=statusCd;
    $('#planList').datagrid("load",defaultParameter);
}


function _callBackOrg(projectId,projectName){
  $("#belongPlan").val(projectId);
  queryPurchasePlan();
}

function _callModelUnit(orgId,orgName){
  $("#orgList").val(orgId).change();
}

function _callBackForUnit(orgId,orgName){
  $("#orgId").val(orgId);
  queryPurchasePlan();
}

function _callBackProjectInfo(projectId,projectName){
  $("#projectName").val(projectId).change();
}
function exportList(){
	var param = {
		    "classes": "PurchaseService",
		    "fileName": "采购计划列表",
		    "method": "queryPurchasePlanListByCondition",
		    "title": {
		        "impleProjName":"实施项目名称",
		        "purchPlanName":"采购计划名称",
		        "purchPlanCode": "计划编号",
		        "purchWay": "采购方式",
		        "prepayTotal": "预算金额",
		        "planType": "计划类型",
		        "orgName": "代理机构",
		        "giveDt": "下达时间",
		        "statusName": "状态"
		    }
		};
	param.param={};
	var impleProjName=$("#planName").val().trim();
    var planProjId=$("#belongPlan").val().trim();
    var orgId=$("#unitOut").val().trim();
    param.param.impleProjName=impleProjName;
    param.param.planProjId=planProjId;
    param.param.orgId=orgId;
	var url='/InfoManageWeb/commonService/export?json='+encodeURI(JSON.stringify(param));
	window.open(url, '_blank');
}


function CreateFormPage(strPrintName, printDatagrid) {
	 var tableString = '<table cellspacing="0" class="pb" style="TABLE-LAYOUT: fixed">';
	 var frozenColumns = printDatagrid.datagrid("options").frozenColumns;  // 得到frozenColumns对象
	 var columns = printDatagrid.datagrid("options").columns;    // 得到columns对象
	 var nameList = '';
	
	 // 载入title
	 if (typeof columns != 'undefined' && columns != '') {
	     $(columns).each(function (index) {
	         tableString += '\n<tr>';
	         if (typeof frozenColumns != 'undefined' && typeof frozenColumns[index] != 'undefined') {
	             for (var i = 1; i < frozenColumns[index].length-1; ++i) {
	                 if (!frozenColumns[index][i].hidden) {
	                     tableString += '\n<th width="' + frozenColumns[index][i].width + '"';
	                     if (typeof frozenColumns[index][i].rowspan != 'undefined' && frozenColumns[index][i].rowspan > 1) {
	                         tableString += ' rowspan="' + frozenColumns[index][i].rowspan + '"';
	                     }
	                     if (typeof frozenColumns[index][i].colspan != 'undefined' && frozenColumns[index][i].colspan > 1) {
	                         tableString += ' colspan="' + frozenColumns[index][i].colspan + '"';
	                     }
	                     if (typeof frozenColumns[index][i].field != 'undefined' && frozenColumns[index][i].field != '') {
	                         nameList += ',{"f":"' + frozenColumns[index][i].field + '", "a":"' + frozenColumns[index][i].align + '"}';
	                     }
	                     tableString += '>' + frozenColumns[0][i].title + '</th>';
	                 }
	             }
	         }
	         for (var i = 1; i < columns[index].length-1; ++i) {
	             if (!columns[index][i].hidden) {
	                 tableString += '\n<th width="' + columns[index][i].width + '"';
	                 if (typeof columns[index][i].rowspan != 'undefined' && columns[index][i].rowspan > 1) {
	                     tableString += ' rowspan="' + columns[index][i].rowspan + '"';
	                 }
	                 if (typeof columns[index][i].colspan != 'undefined' && columns[index][i].colspan > 1) {
	                     tableString += ' colspan="' + columns[index][i].colspan + '"';
	                 }
	                 if (typeof columns[index][i].field != 'undefined' && columns[index][i].field != '') {
	                     nameList += ',{"f":"' + columns[index][i].field + '", "a":"' + columns[index][i].align + '"}';
	                 }
	                 tableString += '>' + columns[index][i].title + '</th>';
	             }
	         }
	         tableString += '\n</tr>';
	     });
	 }
	 // 载入内容
	 var rows = printDatagrid.datagrid("getRows"); // 这段代码是获取当前页的所有行
	 var nl = eval('([' + nameList.substring(1) + '])');
	 for (var i = 0; i < rows.length; ++i) {
	     tableString += '\n<tr>';
	     $(nl).each(function (j) {
	         var e = nl[j].f.lastIndexOf('_0');
	
	         tableString += '\n<td';
	         if (nl[j].a != 'undefined' && nl[j].a != '') {
	             tableString += ' style="text-align:' + nl[j].a + ';style="WORD-WRAP: break-word" width="20"';
	         }else{
	        	 tableString += ' "TABLE-LAYOUT:fixed;WORD-BREAK:break-all" width="20"';
	         }
	         tableString += '>';
	         if (e + 2 == nl[j].f.length) {
	             tableString += rows[i][nl[j].f.substring(0, e)];
	         }
	         else
	             tableString += rows[i][nl[j].f];
	         tableString += '</td>';
	     });
	     tableString += '\n</tr>';
	 }
	 tableString += '\n</table>';
	  $("#printdata").val(tableString);
	 var popupwin =window.open("print", '_blank');
}

function initOrg(){
  var client = new com.im.common.ajax();
  var result = client.callAsJson("userService/queryOrgarizationsByCond", {"forOrgList": "","orgType":40});

  if(!result.success){
    toastr.error(result.resultMsg);
  }else{
    console.log(result);
    result.result.unshift({'orgId':'','orgName':'请选择'});
    $.each( result.result, function (i) {
      $('#orgList').append("<option value=" + result.result[i].orgId + ">" +result.result[i].orgName + "</option>");

    });
    $("#orgList").select2({});
  }
}

$("#uploadBtn").click(function(){
    saveUploadInfo();
});

var curIndex=-1;
var tmpfiles;//文件上传下载
var file = new com.im.common.file();
tmpfiles = file.activate(1);
$('#common_file').val('');
$('#common_file_name').hide();

function uploadFileModel(index){
    curIndex=index;

    $('#addFileModal').modal("show");
}

function saveUploadInfo(){
    var param={};
    var row = $('#planList').datagrid('getData').rows[curIndex];
    var url="/purchaseService/uploadFileToPurchasePlan";
    var fileList = [];
    var client = new com.im.common.ajax();
    //上传文件
    var filename = $('#common_file_name label');
    var files = [];
    for (var i = 0; i < filename.length; i++) {
        if (filename.eq(i).is(':visible')) {
            files.push(filename.eq(i).html());
        }
    }

    if (filename.length > 0) {
        client.callAsFile(tmpfiles.newly, function (result) {
            if (!result.success) {
                toastr.error('文件上传失败！');
                return false;
            } else {
                $.each(result.result, function (index, item) {
                    fileList.push(item);
                });
                param.fileList = fileList;
                param.purchPlanId=row.purchPlanId;
                var client = new com.im.common.ajax();
                var result = client.callAsJson(url, param);
                if (!result.success) {
                    toastr.error(result.resultMsg);
                } else {
                    $('#addFileModal').modal("hide");
                    toastr.info('文件上传成功！');
                }
            }
        });
    }
}

$(function(){

  initPurchWay();

  initStatus();

  // initPlan();

  initTable();


  $("#orgId").project2unit2itemCommpent({
    //elmIdProjectSel : "projectSel",//规划工程下拉元素
    elmIdPlanTypeSel : "planProjClass",
    elmIdUnitSel : "orgId",//组织单位下拉元素
    elmIdItemSel : "implProjectId",//实施项目下拉元素
    orgType : "10",//初始化单位时，单位类型
    callbackFunc: function (callBackType, ret) {//下拉框值改变时回调
      //_callBackOrg(objvalue, objname);
      //callBackType : 1 所属规划值变更 2单位值变更  3项目名称变更
      //ret: orgId,orgName,impleProjId,impleProjName,planProjClass,planProjClassName
      queryPurchasePlan();
    }
  });


  $("#orgInfo").project2unit2itemCommpent({
    //elmIdProjectSel : "projectSel",//规划工程下拉元素
    elmIdPlanTypeSel : "planProjClassInfo",
    elmIdUnitSel : "orgInfo",//组织单位下拉元素
    elmIdItemSel : "implProjectInfo",//实施项目下拉元素
    orgType : "10",//初始化单位时，单位类型
    callbackFunc: function (callBackType, ret) {//下拉框值改变时回调
    }
  });

  //initOrg();



  initPurchType();

  // $("#belongPlan").constantCommpent({
  //   elmIdSel : "belongPlan",//需要展示的位置下拉框
  //   constParamCode : "PLAN_PROJ_CLASS",//需要加载的常量编码
  //   callbackFunc: function (objvalue, objname) {//下拉框值改变时回调
  //   }
  // });

  $("#btn_del").click(function(){
     delPurchasePlanConfirm();
  });


  $("#unitOut").unitselCommpent({
      elmIdSel : "unitOut",//需要展示的位置下拉框
      unitType : "10",//单位类型 为空的时候全部查询
      callbackFunc: function (objvalue, objname) {//下拉框值改变时回调
    	  queryPurchasePlan();
      }
  });

    // $("#orgBtn1").click(function() {
    //         $("#orgText").unitSearchCommpent({
    //             elmIdOut : "orgText",//组织树单击之后回填的文本框（input）
    //             elmIdModal : "unitSearchModal",
    //             hasOrgType: true,//组织树是否先展示组织类型
    //             callbackFunc: function (orgId, orgName) {//组织树单击之后回调函数
    //                 _callModelUnit(orgId, orgName);
    //             }
    //         });
    //     });
  initOrg();






  $("#purchaseStatusCd").change(function(){
     queryPurchasePlan();
  });

  $("#search-btn").click(function(){
     queryPurchasePlan();
  });
  //导出
  $('#btn_export').click(function (){
	  exportList();
  });

 
  $('#btn_print').click(function (){
	  CreateFormPage("采购计划", $('#planList'))
  });
  $("#btn_reset").click(function(){
    reset();
  });
 //规划工程变更事件
  $("#belongPlan").change(function(){
	  queryPurchasePlan();
  });

  $("#btn_add").click(function(){
    $('#purchasePlanModal').modal({
      backdrop: false,//点击空白处不关闭对话框
      keyboard: false,//键盘关闭对话框
      show:true//弹出对话框
    });
    var mydate = new Date();
//    console.log($("#orgInfo option:eq(1)").html());
	$("#orgInfo option:eq(1)").attr("selected",true);
    $("#orgInfo").trigger("change");
    $("#planProjClassInfo  option:eq(1)").attr("selected",true);
    $("#planProjClassInfo").trigger("change");
    $("#implProjectInfo  option:eq(1)").attr("selected",true);
    $("#implProjectInfo").trigger("change");
     var year=mydate.getFullYear(); //获取完整的年份(4位,1970-????)
     $("#purchPlanCode").val("湘财计采〔"+year+"〕");
      // var client = new com.im.common.ajax();
      // var param={};
      // param.tableName="T_PURCHASE_PLAN";
      //    var result = client.callAsJson("commonService/getSeq",param);
      //     if(result.resultCode!=0){
      //       toastr.error(result.resultCode);
      //      }else{
      //       console.log(result.result.seq);
      //       $("#purchPlanCode").val(result.result.seq);
      //      }

      //预算总价默认0
      $("#prePayTotal").val('0');

      $("#prePayTotal").focus(function() {
          if($("#prePayTotal").val() == undefined || $("#prePayTotal").val() == '0' || tmpval == '0.00'){
              $("#prePayTotal").val('');
          }
      })
  });

  $('#purchasePlanModal').on('hidden.bs.modal', function () {
    availableModelField();
    $("#purchWay").val("").trigger("change");
    $("#orgList").val("").trigger("change");
    $("#purchPlanType").val("").trigger("change");
    $("#purchPlanId").val("");
    $('#purchasePlanForm').data('bootstrapValidator').options.excluded = [':disabled'];
    $('#purchasePlanForm').bootstrapValidator('resetForm', true);
    $('#purchasePlanForm')[0].reset();
  });

     $("#itemBtn").click(function() {
            $("#itemBtn").itemSearchCommpent({
                elmIdOut : "projectNameText",//组织树单击之后回填的文本框（input）
                elmIdModal : "itemSearchModal",//用户选择
                elmIdOrgModal : "unitSearchModal",//组织查询
                callbackFunc: function (projectId, projectName) {//组织树单击之后回调函数
                    _callBackProjectInfo(projectId, projectName);
                }
            });
        });
  //时间插件
  $('.datetimepicker').datepicker({
      onSelect:function (){
      	$('.datetimepicker').trigger("change");
          queryPurchasePlan();
      }
  });

  $("#ensureBtn").click(function () {
    savePurchasePlan();
  });

  $("#purchasePlanForm").bootstrapValidator({
    feedbackIcons: {
      valid: 'glyphicon glyphicon-ok',
      invalid: 'glyphicon glyphicon-remove',
      validating: 'glyphicon glyphicon-loadData'
    },
    excluded: [':disabled'],
    fields: {
      implProjectInfo: {
        trigger:"change",
        validators: {
          notEmpty: {
            message: '请选择实施项目'
          }
        }
      },
      purchPlanCode: {
        validators: {
          notEmpty: {
            message: '计划编号不能为空'
          }
        }
      },
//      orgList: {
//        trigger:"change",
//        validators: {
//          notEmpty: {
//            message: '请选择代理机构'
//          }
//        }
//      },
      purchPlanType: {
        validators: {
          notEmpty: {
            message: '请选择计划类型'
          }
        }
      },
      purchPlanName: {
        validators: {
          notEmpty: {
            message: '采购计划名称不能为空'
          }
        }
      },
      purchWay: {
        validators: {
          notEmpty: {
            message: '请选择采购方式'
          }
        }
      },
      prePayTotal:{
              validators: {
                notEmpty: {
                  message: '预算总价不能为空'
                },
            callback: {/*自定义，可以在这里与其他输入项联动校验*/
                 message: '只能输入整数或者小数',
                 callback:function(value, validator,$field){
                     return /^[0-9]+([.]{1}[0-9]+){0,1}$/.test(value);
                 }
             }
              }
      },
      statusCd: {
        validators: {
          notEmpty: {
            message: '请选择状态'
          }
        }
      },
    }
  });

})